package com.monster.starter.redis.utils;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * redis锁
 * @author kuang
 */
@Slf4j
public class RedissonLock extends RedisUtils {
    /**
     * redisson客户端
     */
    protected static RedissonClient client;

    /**
     * 获取一个redis客户端
     * @return redis客户端
     */
    public static RedissonClient getClient () {
        return client;
    }

    /**
     * 公平锁加锁
     * 默认会加锁600秒
     * @param key 唯一锁key
     * @return true/false
     */
    public static boolean fairLock (String key) {
        RLock fairLock = client.getFairLock(key);
        try {
            // 尝试加锁，最多等待10秒，上锁以后600秒自动解锁
            return fairLock.tryLock(10, 600, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("获取锁[{}]失败", key, e);
        }
        return false;
    }

    /**
     * 公平锁解锁
     * @param key 唯一锁key
     */
    public static void fairUnlock (String key) {
        RLock fairLock = client.getFairLock(key);
        fairLock.unlock();
    }

}
